import 'dart:io';

import 'package:copilot_proxy/context.dart';
import 'package:copilot_proxy/header_manager.dart';
import 'package:copilot_proxy/middleware/logging_middleware.dart';
import 'package:copilot_proxy/routes/routes.dart';
import 'package:copilot_proxy/token_manager.dart';
import 'package:copilot_proxy/utils/network_util.dart';

RestHandler proxyRequest(String targetUrl) {
  final uri = Uri.parse(targetUrl);
  return (Context context) async {
    final String? copilotToken = context['token'];
    final clientId = getClientIdByCopilotToken(copilotToken);
    await TokenManager.instance.useCopilotTokenData(clientId, (token) async {
      if (context.isTokenDataWrong(token)) return;
      final request = await token!.client.postUrl(uri);
      final headers = HeaderManager.instance.getHeaders(uri.path);
      request.setHeaders({
        ...headers,
        HttpHeaders.authorizationHeader: ['Bearer ${token.copilotToken}'],
      });
      request.send(context['body']);
      final resp = await request.close();
      final statusCode = resp.statusCode;
      context.statusCode = statusCode;
      resp.headers.forEach((k, v) => context.response.headers.set(k, v));
      await resp.pipe(context.response);
      if (statusCode == HttpStatus.ok) return;
      token.setExpiry();
    });
  };
}
